(function(){
	var obj={};
	obj.ajax=function(type,url,data,headers,context,callback){
		$.ajax({type:type,url:url,data:JSON.stringify(data),headers:headers,context:context})
		.done(callback);
	};
	window.j=obj;
})();

function showMerchantComponent(template){
	this.model=null;
	this.template=template;
	this.findMerchantsByInputText=function(text){
		j.ajax("GET","findMerchantsByInputText?text="+text,null,null,this,function(merchants){
			this.model=merchants;
			_render(this.model);
		});
	};
	
	
	function _render(data){
		template.empty();
		data.forEach(function(item){
			$("#merchantTemplate").clone(true)
			.css("display","block")
			.find(".mimgTempl").attr("src",item.portrait).css("width","200px")
			.css("height","200px").end() 
			.find(".mnameTempl").text(item.mname).end()
			.find(".merchantBtn").attr("icnum",item.icnum).end()
			.appendTo(template);
		});
	}
	
}

function showAdComponent(template){
	this.model=null;
	this.template=template;
	this.findAds=function(){
		j.ajax("GET","http://10.222.29.185:8999/A-version3/ad/onAd",null,null,this,function(advs){
			this.model=advs;
			_render(this.model);
		});
	};
	function _render(data){
		template.empty();
		var i = 0;
		
		if(data==""){
			$("<div>").addClass("item").addClass("active")
			.append($("<img>").attr("src","images/001.jpg").attr("alt","正在加载图片"))
			.append($("<div>").attr("class","carousel-caption").append($("<p>").text("欢迎打广告")))
			.appendTo(template);
			$("<li>").attr("data-target","#carousel-example-generic").attr("data-slide-to",i).addClass("active")
			.appendTo("#adHookOl");
		}else{
			data.forEach(function(item){
				if(i==0){
					$("<div>").addClass("item").addClass("active")
					.append($("<img>").attr("src",item.picUrl).attr("alt","正在加载图片"))
					.append($("<div>").attr("class","carousel-caption").append($("<p>").text(item.slogan)))
					.appendTo(template);
					$("<li>").attr("data-target","#carousel-example-generic").attr("data-slide-to",i).addClass("active")
					.appendTo("#adHookOl");
					i++;
				}else{
					$("<div>").addClass("item")
					.append($("<img>").attr("src",item.picUrl).attr("alt","正在加载图片"))
					.append($("<div>").attr("class","carousel-caption").append($("<p>").text(item.slogan)))
					.appendTo(template);
					$("<li>").attr("data-target","#carousel-example-generic").attr("data-slide-to",i)
					.appendTo("#adHookOl");
				}
			});
		}
		
		
	}
	
}


$(function(){
	var c = new showMerchantComponent($("#merchantId"));
	var d = new showAdComponent($("#adHook"));
	d.findAds();
	
	$("#findMerchantText").bind('input propertychange',function(){
		var text = $(this).val();
		c.findMerchantsByInputText(text);
	});
	$(".merchantBtn").on("click",function(){
		var icnum  = $(this).attr("icnum");
		window.location.href="toCartPage?icnum="+icnum;
	});
	$("#allFoods").on("click",function(){
		
	});
});

